import wx from 'weixin-js-sdk'
import { config } from '@/api/appApi'
interface statusType {
  appId: String
  timestamp: Number
  nonceStr: String
  signature: String
}

const state = {
  appId: '',
  timestamp: 0,
  nonceStr: '',
  signature: ''
} as statusType

const mutations = {
  UPDATE_CONFIG: (state, payload) => {
    state.appId = payload.appId
    state.timestamp = payload.timestamp
    state.nonceStr = payload.nonceStr
    state.signature = payload.signature
  }
}
/** config接口注入权限验证配置*/
const actions = {
  config({ commit }, payload) {
    const wxappId = import.meta.env.VITE_APP_APPID
    const host = location.href
    config({ appid: wxappId, url: encodeURI(host) }).then((res) => {
      const { data } = res
      console.log(payload)
      commit('UPDATE_CONFIG', {
        appId: data.appid,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature
      })
      if (payload) {
        wx.config({
          debug: false,
          appId: data.appid,
          timestamp: data.timestamp,
          nonceStr: data.nonceStr,
          signature: data.signature,
          jsApiList: payload
        })
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
